package com.wjk.kylin.rpc.core.netty.client;

import com.wjk.kylin.rpc.core.invoker.RpcConsumerFactory;
import com.wjk.kylin.rpc.core.netty.params.RpcResponse;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author wjk
 */
@ChannelHandler.Sharable
public class NettyClientHandle extends SimpleChannelInboundHandler<RpcResponse> {
    private static final Logger LOGGER = LoggerFactory.getLogger(NettyClientHandle.class);

    private final RpcConsumerFactory consumerFactory;

    public NettyClientHandle(RpcConsumerFactory consumerFactory) {
        this.consumerFactory = consumerFactory;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcResponse response) throws Exception {
        LOGGER.debug(">>>>>>>>>>> kylin-rpc netty client response {}", response);

        // notify response
        consumerFactory.notifyConsumerFuture(response.getRequestId(), response);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        LOGGER.error(">>>>>>>>>>> kylin-rpc netty client caught exception", cause);
        ctx.close();
    }

}
